package com.byq.mm.smartlib.component;


import android.content.Context;
import android.graphics.Canvas;
import android.view.View;

import com.byq.mm.smartlib.util.GraphicsUtil;

public class SensorView extends View {
	short type;
	ValueController controller = new ValueController();
	String deviceName;
	int max;
	public void update(int value, int m) {
		max = m;
		controller.prepare(value);
		postInvalidate();
	}

	public SensorView(Context ctx, int vmax, int value, short type, String name) {
		super(ctx);
		max = vmax;
		this.type = type;
		controller.prepare(value);
		this.deviceName = name;

	}

	@Override
	protected void onLayout(boolean changed, int left, int top, int right,
			int bottom) {
		// TODO Auto-generated method stub
		super.onLayout(changed, left, top, right, bottom);
		// Bitmap bmp = GraphicsUtil.panelImage(right, bottom);

		// Drawable drawable = new BitmapDrawable(bmp);
		// this.setBackgroundDrawable(drawable);
	}

	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		int v = controller.take();
		int w = this.getWidth();
		int h = this.getHeight();
		int r = Math.min(w, h) / 3;
		if (type == 0){
			int step = max/10;
			int sstep = step/5;
			if(sstep == 0)
				sstep = 1;
			sstep = normalize(sstep);
			step = sstep * 5;
			step = normalize(step);
			sstep = step/5;
			max = step * 10;
			GraphicsUtil.drawPanel(canvas, new int[] { v }, w / 2, h / 2, r,
					max, step, sstep, deviceName);
		}
		if (type == 1)
			GraphicsUtil.drawMeter(canvas, (double) v, w / 2, 50, 10.0f, 30.0f,
					15);
		if (!controller.finished())
			invalidate();
	}
	int normalize(int sstep){
		int l = Integer.toString(sstep).length();
		String h = "1";
		for(int i = 0; i < l-1; i++)
			h += "0";
		int hh = Integer.parseInt(h);
		double kk = ((double)sstep)/hh;
		int n = (int) Math.ceil(kk);
		n = n * hh;
		return n;
	}

}

class ValueController {
	int current;
	int start;

	static final int freq = 20;
	int count = 0;

	public void prepare(int v) {

		start = current;
		current = v;
		count = 0;
	}

	boolean finished() {
		return count == freq;
	}

	public int take() {
		if (finished())
			return current;
		double r = ((double) count) / freq;
		count++;
		return (int) (r * (current - start) + start);

	}

}